
Page({

  data: {
    rank:"-",
    tabbarHeight:"",
    animationData: {},
    showShade:false,
    time:"",
    showDailyQuestion:false,
    statusBarHeight: wx.getStorageSync('statusBarHeight') + 'px',
    navigationBarHeight: wx.getStorageSync('navigationBarHeight') + 'px',
    menuButtonHeight: wx.getStorageSync('menuButtonHeight') + 'px',
    navigationBarAndStatusBarHeight: wx.getStorageSync('statusBarHeight')+wx.getStorageSync('navigationBarHeight')+'px',
    minusHeight:wx.getStorageSync('statusBarHeight')+wx.getStorageSync('navigationBarHeight'),
    hasDone:false,
    sevenDaysNotDone:true,
    topBookList:[],
    todayPracticeNum:0,
    rate:0,
    continuedDays:0,
    usingInfoList:[],
    allUsingBookList:[],
    countDownNum:"-",
    informList:[{"text":"加载中..."}],
    isUsing:false,
    daily:{"question":"加载中..."},
    reviewNum:"0",
    model:false,


    list: [
      {
        "text": "首页",
        
        "iconPath": "/images/home.png",
        "selectedIconPath": "/images/home_active.png"
      },
      {
        "text": "文库",
        
        "iconPath": "/images/library.png",
        "selectedIconPath": "/images/library_active.png"
      },
      {
        "text": "社区",
        
        "iconPath": "/images/community.png",
        "selectedIconPath": "/images/community_active.png"
      },
      {
        "text": "我的",
        
        "iconPath": "/images/user.png",
        "selectedIconPath": "/images/user_active.png"
      }
    ]
  },



  onLoad: function (options) {
    


    let date = new Date()
    const hour = date.getHours()
    let time = ""
    if(hour >= 6 && hour <= 8){
      time = "早上好"
    }else if(hour >= 9 && hour <= 11){
      time = "上午好"
    }else if(hour >= 12 && hour <= 17){
      time = "下午好"
    }else if(hour >= 18 && hour <= 19){
      time = "傍晚好"
    }else if(hour >= 20 && hour <= 23){
      time = "晚上好"
    }else if(hour >= 0 && hour <= 5){
      time = "凌晨好"
    }
    this.setData({time:time})
    
    let app = getApp()

    if (app.globalData.checkLogin){
      

      if(!app.globalData.newUser){
        this.updateUser()
        this.showCard()
        this.showUsing()
        this.review()
      }
      this.showInform()
      this.showDaily()
      this.getSetting()
    }else{
      app.userInfoReadyCallback = res => {
        if(!app.globalData.newUser){
          this.updateUser()
          this.showCard()
          this.showUsing()
          this.review()
        }
        this.showInform()
        this.showDaily()
        this.getSetting()
      };
    }

    wx.request({
      url: app.globalData.url + '/book/list',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: result => {
        let allBookList = result.data.data
        for(let i = 0; i < allBookList.length; ++i){
          allBookList[i].coverImg = app.globalData.url + "/" + allBookList[i].coverImg
        }
        app.globalData.allBookList = allBookList
        let topBookList = allBookList.slice(0,3)
        this.setData({
          topBookList :topBookList
        })
      }
    })
    
    
    wx.request({
      url: app.globalData.url + '/book/days',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: result => {
        let countDownNum = result.data.data
        countDownNum = countDownNum * -1
        this.setData({
          countDownNum:countDownNum,
        })
      }
    })
  },
  
  updateUser: function(){
    let app = getApp()
    let _userInfo = this.processUserInfo()
    wx.request({
      url: app.globalData.url + '/user/update',
      method: "POST",
      data: {
        nickname: app.globalData.userInfo.nickName,
        avatar: app.globalData.userInfo.avatarUrl,
        gender: _userInfo.gender,
        address: _userInfo.address,
        id: app.globalData.userInfo.openid,
        score:app.globalData.userInfo.score,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success (res) {
        
      }
    })
  },
  processUserInfo:function(){
    let app = getApp()
    let gender = "man"
    if(app.globalData.userInfo.gender == 0){
      gender = "woman"
    }
    let address = app.globalData.userInfo.country
    if(address == "China" || address == "中国"){
      address = ""
    }
    
    if(app.globalData.userInfo.province != ""){
      address = address + " " + app.globalData.userInfo.province
    }
    if(app.globalData.userInfo.city != ""){
      address = address + " " + app.globalData.userInfo.city
    }
    return {"gender":gender,"address":address}
  },
  getSetting:function(){
    let app = getApp()
    wx.request({
      url: app.globalData.url + '/home/setting',
      success: result => {
        let setting = result.data.data
        setting = JSON.parse(setting)
        console.log(setting)
        app.globalData.setting = setting
      }
    })

  },

  goToDetail:function(event){
    let app = getApp()
    let postId = event.currentTarget.dataset.postId
    let openId = event.currentTarget.dataset.userId
    wx.request({
      url: app.globalData.url + '/community/informpost',
      data:{
        openId:openId,
        postId:postId,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: result => {
        let post = result.data.data
        if(post.imgPath != ""){
          post.imgPath = post.imgPath.split(",")
          for(let j = 0; j < post.imgPath.length; ++j){
            post.imgPath[j] = app.globalData.url + "/" + post.imgPath[j]
          }
        }else{
          post.imgPath = []
        }
        app.globalData.selectedPost = post
        wx.navigateTo({
          url: '/pages/detail/detail',
        })
      }
    })
  },
  showDaily:function(){
    let app = getApp()
    wx.request({
      url: app.globalData.url + '/home/daily',
      data:{
        openId:app.globalData.userInfo.openid,
      },
      success: result => {
        let daily = result.data.data
        this.setData({daily:daily})
      }
    })
  },
  showUsing:function(){
    let app = getApp()
    wx.request({
      url: app.globalData.url + '/book/using',
      data:{
        openId:app.globalData.userInfo.openid
      },
      header: {
        'content-type': 'application/json' 
      },
      success: result => {
        let allUsingBookList = result.data.data
        //usingInfo = JSON.parse(usingInfo)
        for(let i = 0; i < allUsingBookList.length; ++i){
          allUsingBookList[i] = JSON.parse(allUsingBookList[i])
          allUsingBookList[i].coverImg = app.globalData.url + "/" + allUsingBookList[i].coverImg
        }
        
        if(allUsingBookList.length < 3 && allUsingBookList.length > 0){
          var usingInfoList = allUsingBookList.slice(0, allUsingBookList.length)
        }else{
          var usingInfoList = allUsingBookList.slice(0, 3)
        }

        let isUsing = allUsingBookList.length > 0 ? true : false 
        app.globalData.allUsingBookList = allUsingBookList
        this.setData({
          allUsingBookList:allUsingBookList,
          usingInfoList:usingInfoList,
          isUsing:isUsing,
        })
      }
    })
  },
  showCard:function(){
    let app = getApp()
    wx.request({
      url: app.globalData.url + '/book/card',
      data:{
        openId:app.globalData.userInfo.openid
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: result => {
        let cardInfo = result.data.data
        cardInfo = JSON.parse(cardInfo)
        console.log(cardInfo)
        this.setData({continuedDays:cardInfo.continuedDays})
        if(cardInfo.todayPracticeNum > 0){
          this.setData({
            hasDone:true,
            todayPracticeNum:cardInfo.todayPracticeNum,
            rate:cardInfo.rate,
          })
        }
        if(cardInfo.rank != -1){
          this.setData({
            rank:cardInfo.rank,
            sevenDaysNotDone:false,
          })
        
        }
      }
    })
  },
  showInform:function(){
    let app = getApp()
    wx.request({
      url: app.globalData.url + '/home/inform',
      
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: result => {
        let informList = result.data.data
        
        this.setData({
          informList:informList,
        })
      }
    })
  },
  
  onReady: function () {
    this.animation = wx.createAnimation({
      duration: 400,
      timingFunction: 'ease',
    })

    let systemInfo = wx.getSystemInfoSync()
	  let windowHeight = systemInfo.windowHeight
    let screentHeight = systemInfo.screenHeight
    let tabBarHeight = screentHeight - windowHeight
    console.log("home页面的tabbar高度：",tabBarHeight)
    wx.setStorageSync('tabBarHeight', tabBarHeight)  
    this.setData({tabbarHeight: tabBarHeight + "px"})
    

    
  },
  translate: function () {
    wx.hideTabBar()
    this.setData({showShade:true})
    let height = wx.getSystemInfoSync().windowHeight;
    this.setData({showDailyQuestion:true})
    this.animation.translateY(-height * 0.40).step()
    this.setData({animation: this.animation.export()})
  },
  hide: function () {
    wx.showTabBar()
    let height = wx.getSystemInfoSync().windowHeight;
    this.setData({showShade:false})
    this.animation.translateY(height * 0.40).step()
    this.setData({animation: this.animation.export()})
    setTimeout(() => {
      this.setData({showDailyQuestion:false})
    }, 500)
  },
  like:function(event){
    let dailyId = event.currentTarget.dataset.dailyId
    let app = getApp()
    let daily = this.data.daily
    if(app.globalData.newUser){
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        duration: 1000
      })  
    }else{
      if(daily.hasLiked == 0){
        wx.request({
          url: app.globalData.url + '/home/like',
          data:{
            openId : app.globalData.userInfo.openid,
            dailyId: dailyId,
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success: result => {
            let status = result.data.status
            if(status == 200){
              daily.hasLiked = 1
              daily.likeNum ++
              this.setData({daily:daily})
            }
          }
        })
      }
    }
    
  },

  collect:function(event){
    let dailyId = event.currentTarget.dataset.dailyId
    let app = getApp()
    let daily = this.data.daily
    if(app.globalData.newUser){
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        duration: 1000
      })  
    }else{
      if(daily.hasCollected == 0){
        wx.request({
          url: app.globalData.url + '/home/collect',
          data:{
            openId : app.globalData.userInfo.openid,
            dailyId: dailyId,
            type: "daily",
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success: result => {
            let status = result.data.status
            if(status == 200){
              daily.hasCollected = 1
              daily.collectionNum ++
              this.setData({daily:daily})
            }
          }
        })
      }
    }
    
  },
  review:function(){
    
    let app = getApp()
    if(app.globalData.newUser){
      
    }else{
      wx.request({
        url: app.globalData.url + '/home/review',
        data:{
          openId : app.globalData.userInfo.openid,
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: result => {
          let reviewList = result.data.data
          let reviewNum = 0
          for(let i = 0; i < reviewList.length; ++i){
            reviewNum += reviewList[i].reviewNum
            reviewList[i].coverImg = app.globalData.url + "/" + reviewList[i].coverImg
          }
          app.globalData.reviewList = reviewList
          this.setData({
            reviewNum:reviewNum,
          })
        }
      })
    }
  },

  goToCatalog:function(event){
    let app = getApp()
    if(app.globalData.newUser){
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        duration: 1000
      })  
    }else{
      let id = event.currentTarget.dataset.bookId
      let bookAbbr = event.currentTarget.dataset.bookAbbr
      wx.navigateTo({
        url: '/pages/catalog/catalog?bookId='+id+"&bookAbbr=" + bookAbbr,
      })
    }
    
  },
  goToReview:function(){
    let app = getApp()
    if(app.globalData.newUser){
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        duration: 1000
      })  
    }else{
      if(this.data.reviewNum == "-"){
        wx.showToast({
          title: '加载中...',
          icon: 'none',
          duration: 1000
        })      
      }else if(this.data.reviewNum == 0){
        wx.showToast({
          title: '暂无题目需复习',
          icon: 'none',
          duration: 1000
        })  
      }else{
        wx.navigateTo({
          url: '/pages/review/review',
        })
      }
    }
  },
  goToMore:function(event){
    let type = event.currentTarget.dataset.type
    if(type == "top"){
      wx.navigateTo({
        url: '/pages/more/more'
      })
    }else{
      wx.navigateTo({
        url: '/pages/moreusing/moreusing'
      })
    }
    
  },
  
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }

    



    
  },

  
  onHide: function () {
  },

  
  onUnload: function () {
  },
  async onPullDownRefresh(){
    let app = getApp()
    if(app.globalData.newUser){
      
    }else{
      wx.showLoading({
        title: '加载中',
      })
      await this.showCard()
      await this.showUsing()
      await this.review()
      await this.showDaily()
      await this.showInform()
      wx.stopPullDownRefresh()
      wx.hideLoading()
    }
  },
  onReachBottom: function () {
  },
  onShareAppMessage: function () {
  }
})